/******************************************************************************
 * Copyright (C) 2011 ShenZhen ComTop Information Technology Co.,Ltd
 * All Rights Reserved.
 * 本软件为深圳康拓普开发研制。未经本公司正式书面同意，其他任何个人、团体不得使用、
 * 复制、修改或发布本软件.
 *****************************************************************************/

package com.code.common.utils;

import java.io.IOException;
import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.TimeUnit;

import org.apache.commons.lang.SystemUtils;

/**
 * 强制命令超时类
 * 
 * @author 陈大周
 * @since 1.0
 * @version 2012-9-27 陈大周
 */
public class CommandTimeoutUtils implements Runnable {
    
    BlockingQueue<Object> mailbox = null;
    
    String command = null;
    
    /**
     * ping服务器
     * 
     * @param hostName
     * @param timeout
     * @param unit
     * @return Process
     */
    public static Process commandTimeout(String hostName, long timeout, TimeUnit unit) {
        BlockingQueue<Object> mailbox = new ArrayBlockingQueue<Object>(1);
        Thread objThread = new Thread(new CommandTimeoutUtils(mailbox, hostName));
        objThread.start();
        Object result = null;
        try {
            result = mailbox.poll(timeout, unit);
            if (result == null) {
                if (!mailbox.offer("")) {
                    result = mailbox.take();
                }
            }
        } catch (InterruptedException e) {
        }
        return (Process) result;
    }
    
    /**
     * 构造函数
     * 
     * @param mailbox
     * @param hostName
     */
    CommandTimeoutUtils(BlockingQueue<Object> mailbox, String command) {
        this.mailbox = mailbox;
        this.command = command;
    }
    
    /**
     * @see java.lang.Runnable#run()
     */
    public void run() {
        Process objProcess;
        try {
            if (SystemUtils.IS_OS_WINDOWS) {
                objProcess = Runtime.getRuntime().exec(new String[] { "cmd", "/c", command });
            } else {
                objProcess = Runtime.getRuntime().exec(new String[] { "/bin/sh", "-c", command });
            }
            mailbox.offer(objProcess);
        } catch (IOException e) {
        }
    }
}